import postcss from 'postcss';
import { postcssUI2wx } from "../plugin";
import postscss from 'postcss-scss';

const classSelectors1 = [
    'ui-view',
    'ui-scroll-view',
    'ui-swiper',
    'ui-swiper-item',
    'ui-image',
    'ui-text',
    'ui-rich-text',
    'ui-progress',
    'ui-button',
    'ui-checkbox',
    'ui-form',
    'ui-input',
    'ui-label',
    'ui-picker',
    'ui-picker-view',
    'ui-radio',
    'ui-switch',
    'ui-textarea',
    'ui-navigator',
    'ui-audio',
    'ui-image',
    'ui-video',
    'ui-map'
];

const classSelectors2 = [
    'ui-accordion',
    'ui-badge',
    'ui-blur',
    'ui-calendar',
    'ui-calendar1',
    'ui-cascader',
    'ui-check-list',
    'ui-count-down',
    'ui-count-up',
    'ui-divider',
    'ui-fixed-view',
    'ui-index-list',
    'ui-mask',
    'ui-mini-star',
    'ui-nav-bar',
    'ui-popover',
    'ui-popup',
    'ui-roller',
    'ui-roller-item',
    'ui-row-list',
    'ui-ruler',
    'ui-segment',
    'ui-segment-item',
    'ui-slider',
    'ui-star',
    'ui-stepper',
    'ui-sticky',
    'ui-summary',
    'ui-swipe-out',
    'ui-tab',
    'ui-tabs',
    'ui-tags',
    'ui-timeline',
    'ui-timeline-item',
    'ui-v-calendar',
    'ui-v-tab',
    'ui-v-tabs',
    'ui-w-calendar'
];


export class UiStyle {
    constructor(public source: string, public isApp?: Boolean | undefined) {
    }

    async generator() {
        let code = this.source;
        code = this.transformSelectors(code);
        code = await this.removeUselessRules(code);
        if (this.isApp) {
            code = code.replace(/@import.*;\n/g, '');
            code = `@import './static/styles/index.less';\n` + code;
        }
        return code;
    }

    transformSelectors(code: string) {
        return code.replace(/\.(ui(-[\w]+)+)/g, ($1, $2) => {
            if (classSelectors1.indexOf($2) > -1) {
                return $2.replace('ui-', '');
            }
            if (classSelectors2.indexOf($2) > -1) {
                return $2;
            }
            return $1;
        });
    }

    async removeUselessRules(code: string) {
        code = code.replace(/(\.(\w|-)+\s?\((\w|,|\s|#)*\);?)/g, '/***###$1###***/');

        code = (await postcss([
            postcssUI2wx
        ])
            .process(code, {
                parser: postscss.parse,
            })
            .then(result => result.css)
            .catch(error => {
                console.error('Error processing CSS:', error);
            })
        )!;

        return code.replace(/(\/[*]{3}[#]{3})|([#]{3}[*]{3})\//g, '');
    }
}
